package com.th.config.async;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义异步线程池的配置
 * @author 涂航
 */
@Slf4j
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //线程池核心线程数量 默认1
        executor.setCorePoolSize(10);
        //线程池最大线程数量 当线程的核心线程数量满，以及缓存队列数量满，则会申请超过核心线程的数量
        executor.setMaxPoolSize(20);
        //线程缓存队列数量
        executor.setQueueCapacity(20);
        //超出核心线程范围外的线程最大空闲时间
        executor.setKeepAliveSeconds(20);
        //线程名前缀
        executor.setThreadNamePrefix("Zero_Async_");
        //关闭程序也要使，当线程任务执行完，设置等待60m
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        //线程池任务拒绝策略 当任务队列满了直接报异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //线程池初始化
        executor.initialize();

        //当任务队列满了直接报异常
        //new ThreadPoolExecutor.AbortPolicy();
        //当线程池数量满了后,抛弃线程池中最后一个要执行的任务,换成新的
        //new ThreadPoolExecutor.DiscardOldestPolicy();
        //当线程池数量满了后,不做任何动作，当前任务直接丢弃
       // new ThreadPoolExecutor.DiscardPolicy();

        return executor;
    }

    /**
     * 定义异步任务异常处理类
     * @return
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }



    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler{

        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            log.info("异步任务异常：{}，方法：{}，参数：{}",throwable.getMessage(),method, JSON.toJSONString(objects));
            throwable.printStackTrace();

            //TODO 后置处理 邮箱短信通信
        }
    }



}
